package com.wonders.qxmanager.utils;

import java.util.ArrayList;

public class PageArrayList<V> extends ArrayList<V> {

	private static final long serialVersionUID = 2993495502236872134L;

	private int _total_page_count;

	private int _current_page;

	private int _common_page_size;

	private int _current_page_size;

	private int _total_item_count;

	/**
	 * 构造一个分页的 List
	 * 
	 * @param totalItemCount
	 *            总记录数, 必需大于0
	 * @param commonPageSize
	 *            每页记录数, 必需大于0
	 * @param currentPage
	 *            当前页数, 必需大于0
	 */
	public PageArrayList(int totalItemCount, int commonPageSize, int currentPage) {
		super();
		if (totalItemCount > 0) {
			this._total_item_count = totalItemCount;
		}
		if (commonPageSize > 0) {
			this._common_page_size = commonPageSize;
		}
		if (currentPage > 0) {
			this._current_page = currentPage;
		}
		this._total_page_count = (this._total_item_count
				+ this._common_page_size - 1)
				/ this._common_page_size;
		if (this._current_page == this._total_page_count
				&& this._total_item_count % this._common_page_size != 0) {
			this._current_page_size = this._total_item_count
					% this._common_page_size;
		} else {
			this._current_page_size = (this._current_page > this._total_page_count) ? 0
					: this._common_page_size;
		}
	}

	/**
	 * 得到每页大小
	 * 
	 * @return 每页大小
	 */
	public int getCommonPageSize() {
		return this._common_page_size;
	}

	/**
	 * 得到当前页数
	 * 
	 * @return 当前页数
	 */
	public int getCurrentPage() {
		return this._current_page;
	}

	/**
	 * 得到总页数
	 * 
	 * @return 总页数
	 */
	public int getTotalPageCount() {
		return this._total_page_count;
	}

	/**
	 * 得到当前页中总记录数, 除非位于最后一页, 一般它等于每页大小
	 * 
	 * @return 当前页中总记录数, 当前页不存在返回 0
	 */
	public int getCurrentPageSize() {
		return this._current_page_size;
	}

	/**
	 * 得到总记录数
	 * 
	 * @return 总记录数
	 */
	public int getTotalItemCount() {
		return this._total_item_count;
	}

	/**
	 * 得到首页页号
	 * 
	 * @return 首页页号, 一页没有时返回 0
	 */
	public int getFirstPage() {
		return (this._total_page_count == 0) ? 0 : 1;
	}

	/**
	 * 得到末页页号
	 * 
	 * @return 末页页号, 一页没有时返回 0
	 */
	public int getLastPage() {
		return this._total_page_count;
	}

	/**
	 * 得到前一页页号
	 * 
	 * @return 前一页页号, 没有前一页返回 0
	 */
	public int getPrePage() {
		return (this._current_page > 1) ? this._current_page - 1 : 0;
	}

	/**
	 * 得到下一页页号
	 * 
	 * @return 下一页页号, 没有下一页返回 0
	 */
	public int getNextPage() {
		return (this._current_page < this._total_page_count) ? this._current_page + 1
				: 0;
	}

	/**
	 * 得到相邻一组页的页号
	 * 
	 * @param size
	 *            左右半径范围
	 * @return 相邻一组页的页号
	 */
	public int[] getNeighbouringPage(int size) {
		int left = this._current_page - size;
		int right = this._current_page + size;
		int begin = ((left > 0) ? left : getFirstPage());
		int end = ((right < this._total_page_count) ? right : getLastPage());
		int[] num = new int[end - begin + 1];
		for (int i = 0; i < num.length; i++) {
			num[i] = begin + i;
		}
		return num;
	}

}
